import React, { useEffect } from 'react';
import { Outlet, useSearchParams } from 'react-router-dom';
import { useSettingActions, useSettings } from '../../store/settingStore';
import RightSidebar from './RightSidebar';
import { useMenuActions, useSkipDirect } from '../../store/menuStore';
import { useQuery } from '@tanstack/react-query';
import { CircleLoading } from '@/components/loading';
import MessageClient from './messageClient';
const ContainerLayout = (props) => {
  const [searchParams] = useSearchParams();
  const { showRightSidebar } = useSettings()
  const skipDirect = useSkipDirect()
  const mainStyle = {
    marginLeft: showRightSidebar ? '250px' : undefined,

  };
  const settings = useSettings();
  const { setSettings } = useSettingActions()
  const { getContainerMenus, findByCodeMenu, selectedByCode, setMenuReady } = useMenuActions()

  let { isPending } = useQuery({
    queryKey: ["getContainerMenus"],
    queryFn: async () => {
      const res = await getContainerMenus(searchParams.get('appType') || 1);
      menusChange(res)
      return res
    },
  })

  const sliderOpen = () => {
    setSettings({
      ...settings,
      showRightSidebar: true
    })
  }

  const findFirstChild = (data) => {
    if (data.children && data.children[0]) {
      return findFirstChild(data.children[0])
    } else {
      return data
    }
  }

  const menusChange = (menus) => {
    if (menus) {
      let activeMenu;
      if (searchParams.get('menuCode')) {
        activeMenu = findByCodeMenu(searchParams.get('menuCode'))
      } else if (!searchParams.get('menuUrl') && menus[0]) {
        activeMenu = findFirstChild(menus[0])
      }
      if (activeMenu) {
        if (activeMenu.routerMethod == 2) {
          skipDirect(activeMenu)
        } else {
          selectedByCode(activeMenu)
        }
      }



      setMenuReady(true)
    }
  }

  if (isPending) {
    return <CircleLoading />
  }

  return (
    <div id="container-layout-wrapper">
      <MessageClient />
      <main className="layout-content" style={mainStyle}>{<Outlet />}</main>
      {showRightSidebar ? <RightSidebar /> : <div className='layout-slider-open' onClick={sliderOpen}></div>}
    </div>
  );
};

export default ContainerLayout;
